﻿using Dijiang.Errors;
using Dijiang.Values;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dijiang
{
    public class CmdEnv
    {
        public CmdEnv? parent;
        public Dictionary<string, DValue> variables;

        public CmdEnv()
        {
            variables = new Dictionary<string, DValue>();
        }

        public CmdEnv Copy()
        {
            var result = new CmdEnv();
            result.variables = new Dictionary<string, DValue>(variables);
            return result;
        }

        public DValue Evaluate(DValue val)
        {
            var evaled = val.Eval(this);
            if (evaled is DList quote)
            {
                return new DExpression(quote.items).Eval(this);
            }
            else
            {
                return evaled;
            }
        }

        public DValue Put(DValue symbol, DValue val)
        {
            if (symbol is not DSymbol s) return new WrongTypeError(typeof(DSymbol));

            return Put(s.sym, val);
        }

        public DValue Put(string name, DValue val)
        {
            var saved = val.Eval(this);

            if (variables.ContainsKey(name))
            {
                variables[name] = saved;
            }
            else
            {
                variables.Add(name, saved);
            }

            return saved;
        }

        public DValue Get(string name)
        {
            if (variables.ContainsKey(name))
            {
                return variables[name].Copy();
            }
            else if (parent != null)
            {
                return parent.Get(name);
            }
            else
            {
                return new UndefinedSymbolError(name);
            }
        }
    }
}